import os
import json
import shutil
from typing import Dict, Any, Optional

class PromptConfigManager:
    def __init__(self):
        self.config_dir = "config"
        self.config_file = os.path.join(self.config_dir, "prompt_config.json")
        self.backup_file = os.path.join(self.config_dir, "prompt_config_bak.json")
        self._ensure_config_file()
        
    def _ensure_config_file(self):
        """确保配置文件存在"""
        os.makedirs(self.config_dir, exist_ok=True)
        
        if not os.path.exists(self.config_file):
            # 从 prompt.py 中读取默认配置
            from app.gpt.prompt import BASE_PROMPT, LINK, AI_SUM, SCREENSHOT
            
            default_config = {
                "BASE_PROMPT": BASE_PROMPT,
                "LINK": LINK,
                "AI_SUM": AI_SUM,
                "SCREENSHOT": SCREENSHOT
            }
            
            with open(self.config_file, "w", encoding="utf-8") as f:
                json.dump(default_config, f, ensure_ascii=False, indent=2)
    
    def get_all_prompts(self) -> Dict[str, str]:
        """获取所有提示词配置"""
        with open(self.config_file, "r", encoding="utf-8") as f:
            return json.load(f)
    
    def update_prompt(self, prompt_type: str, content: str) -> bool:
        """更新指定类型的提示词"""
        if prompt_type not in ["BASE_PROMPT", "LINK", "AI_SUM", "SCREENSHOT"]:
            return False
            
        config = self.get_all_prompts()
        config[prompt_type] = content
        
        with open(self.config_file, "w", encoding="utf-8") as f:
            json.dump(config, f, ensure_ascii=False, indent=2)
        
        return True
        
    def restore_from_backup(self) -> bool:
        """从备份文件恢复默认提示词"""
        try:
            if not os.path.exists(self.backup_file):
                return False
                
            # 从备份文件读取默认提示词
            with open(self.backup_file, "r", encoding="utf-8") as f:
                backup_config = json.load(f)
                
            # 更新当前配置
            with open(self.config_file, "w", encoding="utf-8") as f:
                json.dump(backup_config, f, ensure_ascii=False, indent=2)
                
            # 重新加载提示词配置
            from app.gpt.prompt import load_prompts_from_config
            load_prompts_from_config()
            
            return True
        except Exception as e:
            print(f"从备份恢复提示词失败: {e}")
            return False 